package com.lfs.market.controller.admin;

import com.google.code.kaptcha.Producer;
import com.lfs.market.constants.RedisConstant;
import com.lfs.market.model.R;
import com.lfs.market.utils.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin()
public class KaptchaController {
    @Autowired
    private Producer captchaProducer;
    @Autowired
    private RedisTemplate redisTemplate;

    @CrossOrigin
    @GetMapping("/kaptcha")
    public R getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("image/jpeg");
        String capText = captchaProducer.createText();
        redisTemplate.opsForValue().set(RedisConstant.KAPTCHA_KEY, capText, 120, TimeUnit.SECONDS);
        System.out.println(capText);

        BufferedImage image = captchaProducer.createImage(capText);
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.ok(Base64.encode(os.toByteArray()));
    }
}